package cn.com.generaldata.os.ws.impl.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.nutz.ioc.annotation.InjectName;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import cn.com.generaldata.os.constant.FilterConstant;
import cn.com.generaldata.os.constant.ReportConstant;
import cn.com.generaldata.os.paging.Filter;
import cn.com.generaldata.os.paging.FilterRule;
import cn.com.generaldata.os.paging.Page;
import cn.com.generaldata.os.pojo.Area;
import cn.com.generaldata.os.pojo.EnterpriseIndustry;
import cn.com.generaldata.os.pojo.Industry;
import cn.com.generaldata.os.pojo.Role;
import cn.com.generaldata.os.pojo.Unit;
import cn.com.generaldata.os.pojo.User;
import cn.com.generaldata.os.pojo.UserIndustry;
import cn.com.generaldata.os.service.common.AreaService;
import cn.com.generaldata.os.service.common.AuthorityService;
import cn.com.generaldata.os.service.common.IndustryService;
import cn.com.generaldata.os.service.common.UserService;
import cn.com.generaldata.os.util.MD5Util;
import cn.com.generaldata.os.vo.AuthorityVO;
import cn.com.generaldata.os.vo.FuncVO;
import cn.com.generaldata.os.vo.ResultVO;
import cn.com.generaldata.os.vo.UserVO;

@Component
@InjectName
public class UserAction{

	private static final String DEFAULT_PASSWORD = "12345678";

	@Autowired
	private UserService userService;
	
	@Autowired
	private IndustryService industryService;
	
	@Autowired
	private AreaService areaService;

	@Autowired
	private AuthorityService authorService;

	public List<FuncVO> getAllFuncs() {
		return authorService.getAllFuncs();
	}

	public void addAuthor(AuthorityVO vAuthor) {
		if (vAuthor.getId() != null && !"".equals(vAuthor.getId())) {
			authorService.modifyAuthor(vAuthor);
		} else {
			authorService.addAuthor(vAuthor);
		}
	}

	public List<FuncVO> getFuncsByAuthor(String aid) {
		return authorService.getFuncsByAuthor(aid);
	}

	public boolean findUserByAuthor(String aid) {
		Filter filter = new Filter();
		filter.addRule(new FilterRule(FilterConstant.EQUAL, "authorId", aid));
		cn.com.generaldata.os.paging.Result result = userService.queryUsers(filter, null);
		List<User> list = (List<User>) result
				.getOperationResult();
		if (list != null && list.size() > 0) {
			return true;
		}
		return false;
	}

	public void deleteAuthor(String id) {
		authorService.deleteAuthor(id);
	}

	public ResultVO<AuthorityVO> queryAuthority(String name, Integer pageNum) {
		Filter filter = new Filter();
		if (name != null && !"".equals(name)) {
			filter.addRule(new FilterRule(FilterConstant.LIKE, "authorName", "%" + name.trim() + "%"));
		}
		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
		}
		cn.com.generaldata.os.paging.Result result = authorService.queryAuthority(filter, page);
		ResultVO<AuthorityVO> vResult = new ResultVO<AuthorityVO>();
		if (result != null) {
			List<AuthorityVO> operationResult = (List<AuthorityVO>) result.getOperationResult();
			for (AuthorityVO vo : operationResult) {
				boolean enable = findUserByAuthor(vo.getId());
				vo.setEnable(enable);
			}
			vResult.setOperationResult(operationResult);
			vResult.setPageNumber(result.getPageNumber());
			vResult.setPageSize(result.getPageSize());
			vResult.setTotalCount(result.getTotalCount());
		}
		return vResult;
	}

	
	public String createUser(UserVO user) {
		if (user != null) {
			user.setUserPasswd(DEFAULT_PASSWORD);
		}
		String createUser = userService.createUser(toPojo(user));
		user.setId(createUser);
		modifyUserIndustryIds(user);
		addEnterpriseIndustryIds(user);
		return createUser;
	}

	
	public UserVO modifyUser(UserVO user) {
		if (user.getUserIndustrys() != null) {
			modifyUserIndustryIds(user);
		}
		if (user.getEnterpriseIndustrys() != null) {
			addEnterpriseIndustryIds(user);
		}
		return toVo(userService.modifyUser(toPojo(user)));
	}

	
	public UserVO queryUserById(String id) {
		return toVo(userService.queryUserById(id));
	}

	
	public UserVO login(String loginName, String password) {
		return toVo(userService.login(loginName, password));
	}

	
	public UserVO loginNew(String loginName) {
		return toVo(userService.loginNew(loginName));
	}

	
	public ResultVO<UserVO> queryUsersByArea(String loginName, String roleId, String unitName, String areaId,
			Integer pageNum, String unitNo) {
		String hql = "from User where role.id<>'1'";
		HashMap map = new HashMap();
		if (StringUtils.isNotBlank(unitName)) {
			hql += " and userUnit.unitName like :unitName";
			map.put("unitName", "%" + unitName + "%");
		}
		if (StringUtils.isNotBlank(loginName)) {
			hql += " and userLoginname like :loginName";
			map.put("loginName", "%" + loginName + "%");
		}


		if (StringUtils.isNotBlank(roleId)) {
			hql += " and role.id=:roleId";
			map.put("roleId", roleId);
		}
		//替沿海三市的企业报送数据（连云港市、南通市、盐城市）
		//连云港：320700000000000
		//南通：320600000000000
		//盐城：320900000000000
		if (StringUtils.isNotBlank(areaId)) {
			hql += " and area.id=:areaId";
			map.put("areaId", areaId);
		}
		else
			hql += " and area.id in('320700000000000','320600000000000','320900000000000')";
		if (StringUtils.isNotBlank(unitNo)) {
			hql += " and exists(select un.id from Unit un where us.userUnit.id=un.id and un.superCompanyCode= :unitNo)";
			map.put("unitNo", unitNo);
		}
//		if (StringUtils.isNotBlank(areaId)) {
//			hql += " and area.id='" + areaId + "'";
//		}
		hql += " and enterpriseUserUseSystem=1 order by userLoginname";
		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
		}
		return toVoResult(userService.queryUsersHql(hql, page,map));
	}

	
	
	
	public ResultVO<UserVO> queryUsersByParent(String loginName, String roleId, String unitName, String areaId,
			Integer pageNum) {
		List<Area> list = new ArrayList<Area>();
		list = areaService.findChildren(areaId, list);
		List<String> areaIds = new ArrayList<String>();
		areaIds.add(areaId);
		for (int i = 0; i < list.size(); i++) {
			areaIds.add(list.get(i).getId());
		}
		HashMap map = new HashMap();
		String hql = "from User where role.id<>'1'";
		if (StringUtils.isNotBlank(unitName)) {
			hql += " and userUnit.unitName like :unitName";
			map.put("unitName", "%" + unitName + "%");
		}

		if (StringUtils.isNotBlank(loginName)) {
			hql += " and userLoginname like :loginName";
			map.put("loginName", "%" + loginName + "%");
		}

		if (StringUtils.isNotBlank(roleId)) {
			hql += " and role.id=:roleId";
			map.put("roleId", roleId);
		}
		if (areaIds.size() > 0) {
			hql += " and area.id in(:areaId)";
			map.put("areaId", areaIds.toArray());
		}
		hql += " and enterpriseUserUseSystem=1 order by userLoginname";
		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
		}
		return toVoResult(userService.queryUsersByHql(hql, map, page));
	}

	
	public ResultVO<UserVO> queryUsers(String loginName, String roleId, String unitName, Integer pageNum) {
		String hql = "from User where role.id<>'1'";
		HashMap map = new HashMap();
		if (StringUtils.isNotBlank(unitName)) {
			hql += " and userUnit.unitName like :unitName";
			map.put("unitName", "%" + unitName + "%");
		}

		if (StringUtils.isNotBlank(loginName)) {
			hql += " and userLoginname like :loginName";
			map.put("loginName", "%" + loginName + "%");
		}

		if (StringUtils.isNotBlank(roleId)) {
			hql += " and role.id=:roleId";
			map.put("roleId", roleId);
		}
		hql += " and enterpriseUserUseSystem=1 order by userLoginname";
		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
		}
		return toVoResult(userService.queryUsersHql(hql, page,map));
	}

	
	public ResultVO<UserVO> queryExportUsers(String loginName, String roleId, String unitName, Integer pageNum) {
		String hql = "from User where role.id<>'1'";
		HashMap map = new HashMap();
		if (StringUtils.isNotBlank(unitName)) {
			hql += " and userUnit.unitName like :unitName";
			map.put("unitName", "%" + unitName + "%");
		}
		if (StringUtils.isNotBlank(loginName)) {
			hql += " and userLoginname like :loginName";
			map.put("loginName", "%" + loginName + "%");
		}

		if (StringUtils.isNotBlank(roleId)) {
			hql += " and role.id=:roleId";
			map.put("roleId", roleId);
		}

		// 用户标志-1：已经导出，和外网同步 0：新填或修改，没有导出后与外网同步
		hql += " and userFlag='0'";
		hql += " order by userLoginname";
		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
		}
		return toVoResult(userService.queryUsersHql(hql, page,map));
	}

	
	public List<UserVO> queryAllEnterpriseUsers() {
		Filter filter = new Filter();
		filter.setOrder(FilterConstant.ASC);
		filter.setSortBy("userLoginname");
		filter.addRule(new FilterRule(FilterConstant.EQUAL, "enterpriseUserUseSystem", 1));
		filter.addRule(new FilterRule(FilterConstant.ORVALUE, "role.id", "3", "5"));
		return toVoResult(userService.queryUsers(filter, null)).getOperationResult();
	}

	// 按照地区查找企业用户,自加
	
	public List<UserVO> queryAreaEnterpriseUsers(String userAreaId) {
		Filter filter = new Filter();
		filter.setOrder(FilterConstant.ASC);
		filter.setSortBy("userLoginname");
		filter.addRule(new FilterRule(FilterConstant.EQUAL, "enterpriseUserUseSystem", 1));
		filter.addRule(new FilterRule(FilterConstant.ORVALUE, "role.id", "3", "5"));
		if (userAreaId == null) {
			filter.addRule(new FilterRule(FilterConstant.NOT_NULL, "area.id", null));
		} else {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "area.id", userAreaId));
		}
		return toVoResult(userService.queryUsers(filter, null)).getOperationResult();
	}

	// 按照地区查找省区海洋局用户，自加
	
	public List<UserVO> queryAreaOceanUsers(String userAreaId) {
		Filter filter = new Filter();
		filter.setOrder(FilterConstant.ASC);
		filter.setSortBy("userUnit");
		filter.addRule(new FilterRule(FilterConstant.EQUAL, "enterpriseUserUseSystem", 1));
		filter.addRule(new FilterRule(FilterConstant.EQUAL, "role.id", "4"));// 现省局级角色id为4
		filter.addRule(new FilterRule(FilterConstant.EQUAL, "area.id", userAreaId));

		return toVoResult(userService.queryUsers(filter, null)).getOperationResult();
	}

	// 查找所有省区用户
	
	public List<UserVO> queryAllAreaOcean() {
		Filter filter = new Filter();
		filter.setOrder(FilterConstant.ASC);
		filter.setSortBy("userUnit");
		filter.addRule(new FilterRule(FilterConstant.EQUAL, "enterpriseUserUseSystem", 1));
		filter.addRule(new FilterRule(FilterConstant.EQUAL, "role.id", "4"));
		filter.addRule(new FilterRule(FilterConstant.NOT_NULL, "area.id", null));

		return toVoResult(userService.queryUsers(filter, null)).getOperationResult();
	}

	
	public List<UserVO> queryAllUsersByIndustryId(String industryId) {
		if (StringUtils.isNotBlank(industryId)) {
			Filter filter = new Filter();
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "industry.id", industryId));
			List<UserIndustry> userIndustry = userService.getUserIndustry(filter);
			if (userIndustry != null && userIndustry.size() > 0) {
				String hql = "from User as u where (u.role.id=3 or u.role.id=5) and exists (select ui.id from UserIndustry ui where ui.user.id=u.id and ui.industry.id=:industryId) order by u.userLoginname";
				HashMap map = new HashMap();
				map.put("industryId", industryId);
				// Filter filter2 = new Filter();
				// String uids = "";
				// for (UserIndustry ui : userIndustry) {
				// String id = ui.getUser().getId();
				// uids += id + ",";
				// }
				// String[] split = uids.split(",");
				// filter2.setOrder(FilterConstant.ASC);
				// filter2.setSortBy("userLoginname");
				// filter2.addRule(new FilterRule(FilterConstant.COLLECTION, "id", split));
				// filter2.addRule(new FilterRule(FilterConstant.ORVALUE, "role.id", "3", "5"));
				return toVoResult(userService.queryUsersByHql(hql, map, null)).getOperationResult();
			}
		}
		return new ArrayList<UserVO>();
	}

	
	public List<UserVO> selectUser() {
		List<UserVO> users = new ArrayList<UserVO>();
		List<String> areas=new ArrayList<String>();
		areas.add("320700000000000");
		areas.add("320600000000000");
		areas.add("320900000000000");
		String hql="from User u where u.area.id in('320700000000000','320600000000000','320900000000000')  and u.role.id='4'";
			
		users = toVoResult(userService.queryUsersByHql(hql, null, null)).getOperationResult();
		return users;
	}
	
	/**
	 * 查三个市级海洋局，供省统计局代填
	 */
	
	
	public List<UserVO> queryUsersByIndustryId(String industryId, String areaId) {
		List<UserVO> users = new ArrayList<UserVO>();
		List<String> areas=new ArrayList<String>();
		areas.add("320700000000000");
		areas.add("320600000000000");
		areas.add("320900000000000");
		if (StringUtils.isNotBlank(industryId)) {
		String hql="from User u where u.area.id in('320700000000000','320600000000000','320900000000000')  and exists (select ui.id from UserIndustry ui where ui.user.id=u.id and ui.industry.id=:industryId)";
				HashMap map = new HashMap();
		map.put("industryId", industryId);
		
		users = toVoResult(userService.queryUsersByHql(hql, map, null)).getOperationResult();
		}
		return users;
	}

	
	public void removeUsers(List<String> ids) {
		if (ids != null) {
			String[] arrIds = new String[ids.size()];
			ids.toArray(arrIds);

			userService.removeUsers(arrIds);
		}
	}

	@At("/user/modPassword")
	@Ok("json")
	public void changePassword(@Param("loginName") String loginName,@Param("oldPwd") String oldPwd,@Param("newPwd") String newPwd) {
		userService.changePassword(loginName, oldPwd, newPwd);
	}

	
	public void resetPassword(String id) {
		if (id != null) {
			User user = userService.queryUserById(id);
			user.setUserPasswd(MD5Util.getMD5ofStr(DEFAULT_PASSWORD));
			userService.modifyUser(user);
		}
	}

	
	public UserVO modifyUserIndustryIds(UserVO user) {
		return toVo(userService.modifyIndustry(toPojo(user), toPojoIndustrys(user)));
	}

	
	public UserVO addEnterpriseIndustryIds(UserVO user) {
		return toVo(userService.addEnterpriseIndustry(toPojo(user), toPojoEnterpriseIndustrys(user)));
	}

	
	public UserVO deleteUserIndustryIds(UserVO user, String industryId) {
		return toVo(userService.deleteIndustry(toPojo(user), industryId));
	}

	
	public UserVO deleteEnterpriseIndustryIds(UserVO user, String industryId) {
		return toVo(userService.deleteEnterpriseIndustry(toPojo(user), industryId));
	}

	private User toPojo(UserVO user) {
		if (user != null) {
			Role pRole = new Role();
			Area pArea = new Area();
			pRole.setId(user.getRoleId());
			pArea.setId(user.getUserAreaId());

			// Industry pIndustry = null;
			// if (StringUtils.isNotBlank(user.getIndustryId())) {
			// pIndustry = new Industry();
			// pIndustry.setId(user.getIndustryId());
			// }
			Unit unit = null;
			if (StringUtils.isNotBlank(user.getUserUnitId())) {
				unit = new Unit();
				unit.setId(user.getUserUnitId());
				unit.setUnitName(user.getUserUnit());
			}
			return new User(user.getId(), pRole, user.getIndustryId(), pArea,
					user.getUserLoginname(), user.getUserPasswd(), user.getUserRegionName(), user.getUserRegionOcean(),
					user.getUserCityName(), user.getUserDepartmentName(), user.getUserRegionCode(), unit,
					user.getUserInstitutionName(), user.getUserInstitutionCode(), user.getUserDomainName(),
					user.getUserDomainCode(), user.getUserUnitAdmin(), user.getUserStatAdmin(),
					user.getUserFillAdmin(), user.getUserContactPerson(), user.getUserContactPhone(),
					user.getUserFlag(), user.getDl(), user.getZl(), user.getXl(), user.getLm(), user.getHyl(),
					user.getAddr(), user.getQh(), user.getYwhd(), user.getMc(), user.getDwfl(), user.getHy2002(),
					user.getHy2001(), user.getZclx(), user.getKgqk(), user.getJglx(), user.getYyzt(), user.getLsgx(),
					user.getBbdw(), user.getUserStatAdminTel(), user.getUserStat(), user.getUserStatTel(),
					user.getUserFaxTel(), user.getUserEmial(), user.getCompanyUrl(), user.getProduct1(),
					user.getProduct2(), user.getProduct3(), user.getOceanIndustryName(), user.getOceanIndustryCode(),
					user.getMostlyTaking(), user.getSuperCompany(), user.getSuperCompanyCode(), user.getRegistAdd(),
					user.getCompanySynopsis(), user.getUserReportedDataType(), user.getCorporationAndTel(),
					user.getPractitioner(), user.getAssetTotal(), user.getTaking(), user.getEnterpriseUserUseSystem(),
					null, null, null, null, user.getAuthorId());
		}
		return null;
	}

	private List<Industry> toPojoIndustrys(UserVO user) {
		if (user != null) {
			List<Industry> industrys = new ArrayList<Industry>();
			if (user != null) {
				for (String industry : user.getUserIndustrys()) {
					Industry industryId = new Industry();
					industryId.setId(industry);
					industrys.add(industryId);
				}
			}
			return industrys;
		}
		return new ArrayList<Industry>();
	}

	private List<Industry> toPojoEnterpriseIndustrys(UserVO user) {
		if (user != null) {
			List<Industry> industrys = new ArrayList<Industry>();
			if (user != null) {
				for (String industry : user.getEnterpriseIndustrys()) {
					Industry industryId = new Industry();
					industryId.setId(industry);
					industrys.add(industryId);
				}
			}
			return industrys;
		}
		return new ArrayList<Industry>();
	}

	private UserVO toVo(User pUser) {
		if (pUser != null) {
			String roleId = pUser.getRole() == null ? null : pUser.getRole().getId();
			String roleName = pUser.getRole() == null ? null : pUser.getRole().getRoleName();
			String industryId = pUser.getUserIndustryId() == null ? null : pUser.getUserIndustryId();
			String industryName = null;
			String areaId = null;
			String areaName = null;
			if (pUser.getUserUnit() != null && pUser.getUserUnit().getArea() != null) {
				areaId = pUser.getUserUnit().getArea().getId();
				areaName = pUser.getUserUnit().getArea().getAreaDesc();
			}
			String unitId = pUser.getUserUnit() == null ? null : pUser.getUserUnit().getId();
			String unitName = pUser.getUserUnit() == null ? null : pUser.getUserUnit().getUnitName();

			List<String> userIndustrys = new ArrayList<String>();
			if (pUser.getUserIndustrys() != null) {
				for (UserIndustry userIndustry : pUser.getUserIndustrys()) {
					userIndustrys.add(userIndustry.getIndustry().getId());
				}
			}

			List<String> enterpriseIndustrys = new ArrayList<String>();
			if (pUser.getEnterpriseIndustrys() != null) {
				for (EnterpriseIndustry enterpriseIndustry : pUser.getEnterpriseIndustrys()) {
					enterpriseIndustrys.add(enterpriseIndustry.getIndustry().getId());
				}
			}
			if (ReportConstant.YONGHAI_UNIT.equals(roleId)) {
				if (pUser.getUserUnit().getUnitProper() != null) {
					if (pUser.getUserUnit().getUnitProper().indexOf("1") != -1) {
						roleName = "涉海企业用户";
					}
					if (pUser.getUserUnit().getUnitProper().indexOf("2") != -1) {
						roleName = "用海企业用户";
					}
					if (pUser.getUserUnit().getUnitProper().indexOf("3") != -1) {
						roleName = "开发区企业用户";
					}
				}
			}
//			String authorId = pUser.getAuthorId();
//			List<String> funcs = new ArrayList<String>();
//			List<FuncVO> funcsByAuthor = getFuncsByAuthor(authorId);
//			if (funcsByAuthor != null) {
//				for (FuncVO func : funcsByAuthor) {
//					funcs.add(func.getId());
//				}
//			}
			return new UserVO(pUser.getId(), roleId, roleName, industryId, industryName, areaId, areaName,
					pUser.getUserLoginname(),null, pUser.getUserRegionName(),
					pUser.getUserRegionOcean(), pUser.getUserCityName(), pUser.getUserDepartmentName(),
					pUser.getUserRegionCode(), unitName, unitId, pUser.getUserInstitutionName(),
					pUser.getUserInstitutionCode(), pUser.getUserDomainName(), pUser.getUserDomainCode(),
					pUser.getUserUnitAdmin(), pUser.getUserStatAdmin(), pUser.getUserFillAdmin(),
					pUser.getUserContactPerson(), pUser.getUserContactPhone(), pUser.getUserFlag(), pUser.getDl(),
					pUser.getZl(), pUser.getXl(), pUser.getLm(), pUser.getHyl(), pUser.getAddr(), pUser.getQh(),
					pUser.getYwhd(), pUser.getMc(), pUser.getDwfl(), pUser.getHy2002(), pUser.getHy2011(),
					pUser.getZclx(), pUser.getKgqk(), pUser.getJglx(), pUser.getYyzt(), pUser.getLsgx(),
					pUser.getBbdw(), pUser.getUserStatAdminTel(), pUser.getUserStat(), pUser.getUserStatTel(),
					pUser.getUserFaxTel(), pUser.getUserEmial(), pUser.getCompanyUrl(), pUser.getProduct1(),
					pUser.getProduct2(), pUser.getProduct3(), pUser.getOceanIndustryName(),
					pUser.getOceanIndustryCode(), pUser.getMostlyTaking(), pUser.getSuperCompany(),
					pUser.getSuperCompanyCode(), pUser.getRegistAdd(), pUser.getCompanySynopsis(),
					pUser.getUserReportedDataType(), pUser.getCorporationAndTel(), pUser.getPractitioner(),
					pUser.getAssetTotal(), pUser.getTaking(), pUser.getEnterpriseUserUseSystem(), userIndustrys,
					enterpriseIndustrys, pUser.getAuthorId(), new ArrayList<String>());
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	private ResultVO<UserVO> toVoResult(cn.com.generaldata.os.paging.Result pResult) {
		ResultVO<UserVO> result = new ResultVO<UserVO>();

		List<UserVO> users = new ArrayList<UserVO>();
		for (User pUser : (List<User>) pResult
				.getOperationResult()) {
			users.add(toVo(pUser));
		}
		result.setOperationResult(users);
		result.setPageNumber(pResult.getPageNumber());
		result.setPageSize(pResult.getPageSize());
		result.setTotalCount(pResult.getTotalCount());

		return result;
	}

	@At("/user/toModPasswordPage")
	@Ok("jsp:/static/user/modPassword")
	public void toModPasswordPage(){
		
	}
}
